﻿using System.Linq;
using System.Web.Mvc;
using Yonkly.Models;
using Yonkly.Utility;

namespace Yonkly.Controllers
{
    public class FollowersController : BaseController
    {
        protected override void HandleUnknownAction(string username)
        {
            View(username, 0);
        }

        public ActionResult View(string username, int? page)
        {
            page = page ?? 0;
            //get followers
            using (YonklyDataContext dc = new YonklyDataContext())
            {
                BaseViewData baseViewData = GetBaseViewData(username);
                var query = (from f in dc.Friends
                             where f.FriendUser.UserName == username
                             select new FriendItem(baseViewData)
                                        {
                                            Email = f.User.Membership.Email,
                                            UserName = f.User.UserName,
                                            UserId = f.UserId,
                                            Message =
                                                dc.ViewMessages.Count(vm => vm.SenderId == f.UserId) == 0
                                                    ? null
                                                    : new MessageItem(baseViewData,
                                                                      dc.ViewMessages.Where(
                                                                          vm => vm.SenderId == f.UserId).
                                                                          OrderByDescending(m => m.CreatedOn).First())
                                        });
                return View("View",
                           new FollowersViewData(baseViewData)
                               {
                                   Followers =
                                       query.ToPagedList((int)page, Globals.PageSize)
                               });
            }
        }
    }
}